﻿using BridgeWebSystemLib.Core.DataAccess;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;

namespace BridgeWebSystemLib.Core
{
    public class BridgeHttpContext
    {
        private static IServiceProvider _serviceProvider { get; set; }
        public static void Configure(IServiceProvider servicesProvider)
        {
            _serviceProvider = servicesProvider;
        }

        public static HttpContext CurrentHttpContext
        {
            get
            {
                IHttpContextAccessor val = ServiceProviderServiceExtensions.GetRequiredService(_serviceProvider, typeof(IHttpContextAccessor)) as IHttpContextAccessor;
                if (val == null)
                {
                    return null;
                }
                return val.HttpContext;
            }
        }
        
        /// <summary>
        /// 
        /// </summary>
        public static IDataAccess DataAccess
        {
            get
            {
                return GetService<IDataAccess>();
            }
        }

        /// <summary>
        /// 获取指定的服务
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetService<T>()
        {
            return (T)ServiceProviderServiceExtensions.GetRequiredService(_serviceProvider, typeof(T));
        }
        /// <summary>
        /// 从当前请求上下文中获取指定的服务
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetHttpContextService<T>()
        {
            return (T)CurrentHttpContext.RequestServices.GetRequiredService(typeof(T));
        }
    }
}
